import * as Cesium from 'cesium';
import BaseDraw from './common/BaseDraw';
import * as CesiumCoord from './common/CesiumCrood';
import * as CesiumCaculater from './common/CesiumCaculater';
import GroupEntityCollection from '../../Common/GroupEntityCollection';
import { v4 } from 'uuid';
/**
 * 绘制线
 */
export default class DrawPolyline extends BaseDraw {
    constructor(viewer, tip) {
        super(viewer);
        this.viewer = viewer;
        this.tip = tip; // 提示DOM
        this.groupId; // 当前绘制的groupID
        // 事件对象，每种类型的事件只能注册一次
        this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        this.entityCollection = new GroupEntityCollection(viewer); // 集合
    }
    // 重置绘制中间量
    resetDraw() {
        this.groupId = v4(); // 每一次绘制就是一次新的记录
        this.polylineEntity = null; // 当次绘制的-圆实例
        this.labelEntity = null; // 当次绘制的-标签实例
        this.positionList = []; // 当次绘制的笛卡尔数组
    }
    getAllEntity() {
        return this.entityCollection.getAllEntities();
    }
    // 关闭 CallbackProperty的计算，取最后一次的结果
    removeCallbackProperty() {
        if (this.labelEntity) {
            this.labelEntity.position = this.labelEntity.position.getValue();
            this.labelEntity.label.text = this.labelEntity.label.text.getValue();
        }
        if (this.polylineEntity) {
            this.polylineEntity.polyline.positions =
                this.polylineEntity.polyline.positions.getValue();
        }
    }
    createLabelEntity() {
        const positionList = this.positionList;
        console.log('positionList', positionList);
        const entity = new Cesium.Entity({
            position: new Cesium.CallbackProperty(
                () => positionList[positionList.length - 1],
                false
            ),
            label: {
                text: new Cesium.CallbackProperty(() => {
                    const length = CesiumCaculater.distance(positionList); // 计算表路径
                    return length < 1
                        ? `长度:${(length * 1000).toFixed(2)}米`
                        : `长度:${length.toFixed(2)}千米`;
                }, true),
                font: '20px',
                color: Cesium.Color.RED,
                pixelOffset: new Cesium.Cartesian2(0, -20),
                fillColor: Cesium.Color.WHITE,
                showBackground: true,
                backgroundColor: Cesium.Color.BLUE,
            },
        });
        return entity;
    }
    createPolylineEntity() {
        const positionList = this.positionList;
        const entity = new Cesium.Entity({
            polyline: {
                positions: new Cesium.CallbackProperty(() => positionList, false), // CallbackProperty 动态属性
                material: Cesium.Color.YELLOW,
                width: 4,
            },
        });
        return entity;
    }
}

/**
 * 开始绘制折线
 * @param {* 是否显示测量Label} showMeasureLabel
 * @param {* 是否连续绘制} continuousDraw
 */
DrawPolyline.prototype.startDraw = function (showMeasureLabel = true, continuousDraw = true) {
    const _this = this;
    this.tip.show('单击开始绘制');

    this.resetDraw();
    // 左键点击事件
    this.handler.setInputAction(event => {
        const cartesian = CesiumCoord.ScreenToCartesian3(_this.viewer, event.position); // 屏幕坐标转世界坐标
        if (!Cesium.defined(cartesian)) return;
        _this.positionList.push(cartesian.clone());
        // 测量label
        if (showMeasureLabel && !_this.labelEntity) {
            _this.labelEntity = _this.createLabelEntity();
            _this.entityCollection.add(_this.labelEntity, _this.groupId);
        }
        // 折线实体
        if (!_this.polylineEntity) {
            _this.polylineEntity = _this.createPolylineEntity();
            _this.entityCollection.add(_this.polylineEntity, _this.groupId);
        }
        _this.tip.changeText('右键结束绘制');
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    // 鼠标移动事件
    this.handler.setInputAction(event => {
        if (_this.polylineEntity) {
            const cartesian = CesiumCoord.ScreenToCartesian3(_this.viewer, event.endPosition); // 屏幕坐标转世界坐标
            if (!Cesium.defined(cartesian)) return;
            const positionList = _this.positionList;
            console.log('positionList', positionList);
            if (positionList.length <= 1) {
                positionList.push(cartesian.clone());
            } else if (positionList.length >= 2) {
                positionList.pop();
                positionList.push(cartesian.clone());
            }
        }
        const { x, y } = event.endPosition;
        _this.tip.moveTipDOMPosition(x, y); // 改变 TipDOM 位置
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    // 右键点击事件
    this.handler.setInputAction(event => {
        if (this.positionList.length > 0) {
            this.positionList.pop();
        }
        this.endDraw();
        // 连续绘制
        if (continuousDraw) {
            this.startDraw();
        }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};
/**
 * 结束绘制点
 */
DrawPolyline.prototype.endDraw = function () {
    this.tip.close();
    this.removeCallbackProperty(); // 删除callbackproperty
    // 解绑事件
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};
/**
 * 清除绘制的点
 */
DrawPolyline.prototype.removeDraw = function () {
    const entityCollection = this.entityCollection; // entity集合
    entityCollection.removeAll();
};

/**
 * 开始绘制点, Promise 方式，连续绘制放在了外部
 * @param {* 是否显示测量Label} showMeasureLabel
 */
DrawPolyline.prototype.drawPromise = function (showMeasureLabel = true) {
    const _this = this;
    return new Promise((resolve, reject) => {
        try {
            this.tip.show('单击开始绘制');
            this.resetDraw();
            // 左键点击事件
            this.handler.setInputAction(event => {
                const cartesian = CesiumCoord.ScreenToCartesian3(_this.viewer, event.position); // 屏幕坐标转世界坐标
                if (!Cesium.defined(cartesian)) return;
                _this.positionList.push(cartesian.clone());
                // 测量label
                if (showMeasureLabel && !_this.labelEntity) {
                    _this.labelEntity = _this.createLabelEntity();
                    _this.entityCollection.add(_this.labelEntity, _this.groupId);
                }
                // 折线实体
                if (!_this.polylineEntity) {
                    _this.polylineEntity = _this.createPolylineEntity();
                    _this.entityCollection.add(_this.polylineEntity, _this.groupId);
                }
                _this.tip.changeText('右键结束绘制');
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
            // 鼠标移动事件
            this.handler.setInputAction(event => {
                if (_this.polylineEntity) {
                    const cartesian = CesiumCoord.ScreenToCartesian3(
                        _this.viewer,
                        event.endPosition
                    ); // 屏幕坐标转世界坐标
                    if (!Cesium.defined(cartesian)) return;
                    const positionList = _this.positionList;
                    console.log('positionList', positionList);
                    if (positionList.length <= 1) {
                        positionList.push(cartesian.clone());
                    } else if (positionList.length >= 2) {
                        positionList.pop();
                        positionList.push(cartesian.clone());
                    }
                }
                const { x, y } = event.endPosition;
                _this.tip.moveTipDOMPosition(x, y); // 改变 TipDOM 位置
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            // 右键点击事件
            this.handler.setInputAction(event => {
                this.endDraw();
                const entities = this.entityCollection.getEntitiesByGroupId(_this.groupId); // 当前绘制的所有实体
                resolve({
                    entities,
                    positionList: JSON.parse(JSON.stringify(_this.positionList)), // 当前绘制的点坐标集合
                });
            }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        } catch (e) {
            reject(e);
        }
    });
};
